<?php
require_once 'page.php';

class Common{
	
	private $manager;

	public function __construct()
	{
		$this->manager = new MongoDB\Driver\Manager("mongodb://172.17.0.7:27017/testMongo");
	}
	
	/**
	* 查询数据
	*/
	public function index()
	{

        $filter = [];
        //查询记录总的数量
        $commands = [
            'count' => 'users',
            'query' => $filter
        ];
        $command = new MongoDB\Driver\Command($commands);
        $cursor = $this->manager->executeCommand('testMongo', $command);
        $info = $cursor->toArray();
        $count = $info[0]->n;

        $page = new Page($count,10);

        $options = [
            "skip" => $page->firstPage(),
            "limit" => $page->lastPage(),
            'projection' => ['createdate' => 0,
                'expiresdate' => 0,
                'registrant_city' => 0,
                'registrant_street' => 0,
                'registrant_state' => 0,
                'updatedate' => 0,
                'whoisserver_id' => 0,
                'registrar_name_id' => 0,
                'id' => 0,
            ],
        ];
		$query = new MongoDB\Driver\Query($filter, $options);
		$user = $this->manager->executeQuery('testMongo.users', $query);

		return [$user, $page->show()];
	}
	
	/**
	*	添加用户
	*/
	public function addUser()
	{
		$post = $_POST;
		// 插入数据
		$bulk = new MongoDB\Driver\BulkWrite;
		$bulk->insert($post);
		
		$result = $this->manager->executeBulkWrite('testMongo.users', $bulk);
	
	
		if($result->getInsertedCount()){
			echo '<script>';
			echo 'alert("添加成功");';
			echo 'history.go(-2)';
			echo '</script>';
		}
	}
	
	/**
	* 删除文档
	*/
	public function delete()
	{
		$id = new MongoDB\BSON\ObjectId($_GET['id']);
		$bulk = new MongoDB\Driver\BulkWrite;
		$bulk->delete(['_id' => $id]);
		
		$result = $this->manager->executeBulkWrite('testMongo.users', $bulk);
		
		if ($result->getDeletedCount()) {
			echo '<script>';
			echo 'alert("删除成功");';
			echo 'window.location.href=user.php';
			echo '</script>';
		}
	}
}